<?php

namespace tbollmeier\kakuromaster\core\change;

class Transaction {
    
    public static function begin()
    {
        new Transaction();    
    }
    
    public static function exec(Action $action)
    {
        $action->exec();
        if (self::$current !== null) {
            array_push(self::$current->actions, $action);
        }
    }
    
    public static function commit()
    {
        if (self::$current === null) {
            return;
        }
        
        $parent = self::$current->parent;
        if ($parent === null) {
            return;
        }
        
        foreach (self::$current->actions as $action) {
            array_push($parent->actions, $action);
        }
        
        self::$current = $parent;
    }
    
    public static function rollback()
    {
        if (self::$current === null) {
            return;
        }
        
        $actions = array_reverse(self::$current->actions); // undo must be done in reverse order
        foreach ($actions as $action) {
            $action->undo();
        }
        
        self::$current = self::$current->parent;
    }
    
    private static $current = null;
    private $parent;
    private $actions;
    
    private function __construct()
    {
        $this->parent = self::$current;
        $this->actions = [];
        
        self::$current = $this;
    }
    
}
